<template>
  <!-- 最外层容器包裹 -->
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索框 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户按钮 -->
        <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        <el-col :span="4"></el-col>
      </el-row>
      <div class="searchAdd"></div>
      <!-- 用户列表 -->
      <!-- #序号、姓名、邮箱、电话、角色、状态开关、操作（修改、删除、黄色的不知道啥） -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index" label=""></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码 -->

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total,prev, pager, next, jumper, sizes"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addFormClosed">
      <!-- 主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%">
      <!-- 主体区域 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除用户对话框 -->
    <!-- <el-dialog title="删除用户" :visible.sync="deleteDialogVisable" width="50%">
      <span>确定删除该用户吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteUser">确 定</el-button>
      </span>
    </el-dialog> -->
  </div>
</template>

<script>
export default {
  data() {
    // 私有数据
    // 验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }
    // 验证手机号规则
    var checkMobile = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^(13[0-9]|14[014-9]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2 // 当前每页显示多少条数据
      },
      userlist: [],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      deleteDialogVisable: false,
      // 添加用户的数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表的的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度3~10', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度6~15', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editForm: {
        id: 0,
        username: '',
        email: '',
        mobile: ''
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
    // 生命周期函数
  },
  methods: {
    // 函数
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userlist = res.data.users
      this.total = res.data.total
      //   this.total = res.data.users.length
    },

    handleSizeChange(val) {
      // 每页条数变化时
      this.queryInfo.pagesize = val
      console.log(`每页 ${val} 条`)
      this.getUserList()
    },
    handleCurrentChange(val) {
      // 当前页码变化时
      this.queryInfo.pagenum = val
      console.log(`当前页: ${val}`)
      this.getUserList()
    },
    async userStateChanged(userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        this.$message.error('更新用户状态失败！')
        userInfo.mg_state = !userInfo.mg_state
        return
      }
      //   this.$message.success('用户状态已更新')
      console.log('用户状态已更新')
      console.log(userInfo)
    },
    // 监听添加用户对话框的关闭时间
    addFormClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户前进行验证
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        console.log(valid)
        if (!valid) {
          //   this.$message.error('用户信息不合法！')
          return
        }
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) {
          this.$message.error(res.meta.msg)
          return
        }
        this.getUserList()
        this.$message.success('添加成功！')
        this.addDialogVisible = false
      })
    },
    // 修改用户
    async showEditDialog(userInfo) {
      this.editForm.id = userInfo.id
      this.editForm.username = userInfo.username
      this.editForm.mobile = userInfo.mobile
      this.editForm.email = userInfo.email
      // const { data: res } = await this.$http.get(`users/${userInfo.id}`)
      // console.log(res)
      this.editDialogVisible = true
    },
    editUser() {
      this.$refs.editFormRef.validate(async (valid) => {
        console.log(valid)
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(`users/${this.editForm.id}`, this.editForm)
        console.log(res)
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          return
        }
        this.getUserList()
        this.$message.success('更新成功！')
        this.editDialogVisible = false
      })
    },
    // deleteDialog(userInfo) {
    //   this.editForm.id = userInfo.id
    //   this.deleteDialogVisable = true
    // },
    // async deleteUser() {
    //   const { data: res } = await this.$http.delete(`users/${this.editForm.id}`, this.editForm)
    //   if (res.meta.status !== 200) {
    //     this.$message.error('删除失败！')
    //     return
    //   }
    //   this.getUserList()
    //   this.$message.success('用户已删除')
    //   this.deleteDialogVisable = false
    // },
    async removeUserById(id) {
      // 弹框询问
      const confirmres = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)

      if (confirmres !== 'confirm') {
        this.$message('已取消删除')
        return
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        this.$message.error('删除失败！')
        return
      }
      this.getUserList()
      this.$message.success('用户已删除')
    }
  }
}
</script>

<style lang="less" scoped>
// .searchAdd {
//   padding-top: 10px;
//   padding-bottom: 10px;
//   width: 420px;
//   display: flex;
//   justify-content: space-between;
//   .el-input {
//     width: 300px;
//   }
//   .el-button {
//     width: 90px;
//     text-align: center;
//   }
// }
</style>
